package yz;

/**
 * [2. 两数相加](https://leetcode-cn.com/problems/add-two-numbers/)
 *
 * @Author yangz
 * @Date 2022/10/9 23:01
 */
public class LeetCode02_AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();
        ListNode start = head;
        int num = 0;
        while (l1 != null && l2 != null) {
            int i = l1.val + l2.val + num;
            if (i >= 10) {
                start.val = i - 10;
                num = 1;
            } else {
                start.val = i;
                num = 0;
            }
            l1 = l1.next;
            l2 = l2.next;
            if (l1 != null && l2 != null) {
                start.next = new ListNode();
                start = start.next;
            }
        }

        if (l1 == null && l2 == null && num != 0) {
            start.next = new ListNode(1);
        }

        if (l1 != null) {
            calc(num, l1, start);
        }
        if (l2 != null) {
            calc(num, l2, start);
        }
        return head;
    }

    private void calc(int num, ListNode l1, ListNode start) {
        while (l1 != null) {
            start.next = new ListNode();
            start = start.next;
            int i = l1.val + num;
            if (i >= 10) {
                start.val = i - 10;
                num = 1;
            } else {
                start.val = i;
                num = 0;
            }
            l1 = l1.next;
        }
        if (num != 0) {
            start.next = new ListNode(1);
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
